import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {util_d} from "echarts/types/dist/shared";

@Injectable({
  providedIn: 'root',
})
export class HttpService {

  public domain = "https://api.oplatform.maxwebx.cn/api";
  // public domain = "http://localhost:8086/api";

  public user:any = undefined;

  constructor(public http:HttpClient) {

  }

  private request(method: string, url: string, params: any){

    return new Promise((resolve,reject) =>{
      let token = "";
      if (this.user){
        token = this.user.token;
      }
      var headers = {
        'Content-Type': 'application/json; charse=UTF-8',
        Authorization:token,
      }
      this.http.request(method, url, {params, headers:headers}).subscribe( (res: any) => {
        if (res.code == 200 ) {
          if(resolve) resolve(res.data);
        } else {
          if(reject) reject(res.message);
        }
      });
    });

  }


  public get(url:string,params:any){
    url = this.domain + url;
    return this.request("get",url,params);
  }

  public post(url:string,data:any){
    url = this.domain + url;
    return this.request("post",url,data);
  }

  public postBody(url:string,data:any){
    url = this.domain + url;
    return new Promise((resolve,reject) =>{
      let token = "";
      if (this.user){
        token = this.user.token;
      }
      this.http.request("post", url, {
          body:data,
          headers: {
            'Content-Type': 'application/json; charse=UTF-8',
            Authorization:token
          },
        }
      ).subscribe( (res: any) => {
        if (res.code == 200) {
          if(resolve) resolve(res.data);
        }else {
          if(reject) reject(res.message);
        }
      }, (err) => {
        console.log(err);
        if(reject) reject(err);
      });
    });
  }

  public uploadFile(file:File,uid?:string){
    return new Promise((resolve,reject) => {
      const formData: FormData = new FormData();
      formData.append("file",file);
      if (uid){
        formData.append("uid",uid);
      }
      let  url = this.domain + "/common/uploadFile";
      this.http.post(url,formData).subscribe((res:any)=>{
        if (res.code == 200) {
          if(resolve) resolve(res.data);
        }else {
          if(reject) reject(res.message);
        }
      },err=>{
        reject(err);
      });
    });
  }




}
